/**
 * 位 - 循环⬅位移
 */
class Shift {
  constructor(str) {
    this.buf = Buffer.from(str.toString())
    this.byteLength = this.buf.length
    this.bitLength = this.byteLength * 8
    this.resBuf = Buffer.alloc(this.byteLength)
  }
  // 循环位移
  cyclicShift(xIndex) {
    this.byteCyclicShift(xIndex)
  }
  // 字节-循环位移
  byteCyclicShift(xIndex) {
    if (xIndex < 0) {
      console.log('长度不规范')
    } else if (xIndex > this.byteLength) {
      console.log('长度超出！')
    } else if (xIndex === this.byteLength || !xIndex) {
      this.buf.copy(this.resBuf)
    } else {
      this.buf.copy(this.resBuf, 0, xIndex, this.byteLength)
      this.buf.copy(this.resBuf, this.byteLength - xIndex, 0, xIndex)
    }
  }

  // 位-循环位移
  bitCyclicShift(xIndex) {
    if (xIndex < 0) {
      console.log('输入不规范！')
    } else if (xIndex > this.bitLength) {
      console.log('长度超出！')
    } else if (xIndex === this.bitLength || !xIndex) {
      this.buf.copy(this.resBuf)
    } else {
      this.bitMove(xIndex)
    }
  }

  // fn
  bitMove(xIndex) {
    let byteIndex = xIndex >> 3
    let bitRemainder = xIndex & 0x07

    let leftBuf = Buffer.alloc(byteIndex)
    let rightBuf = Buffer.alloc(this.byteLength - byteIndex)

    if (bitRemainder) {
      byteIndex += 1
    }

    let leftBit = this.buf[byteIndex] & (255 - ((1 << bitRemainder) - 1))
    let rightBit = this.buf[byteIndex] & ((1 << (8 - bitRemainder)) - 1)

    this.buf.slice(0, byteIndex).copy(leftBuf)
  }
  // 字节中-位的抓取
  getBit() {}
}

let shift = new Shift(1234567890)

shift.cyclicShift(5)
console.log(shift.buf)
console.log(shift.resBuf.toString('ascii'))
